% Copyright (C) 2019-2023 Benjamin Born, Francesco D'Ascanio, Gernot J. Mueller, Johannes Pfeifer
%
% This is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% It is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% For a copy of the GNU General Public License,
% see <http://www.gnu.org/licenses/>.

%% Creates coefficient matrices required to create Figure 7: Balanced budget government spending shock
 
function store_coefficients_T_G(sign_iter,shock_iter)

% close all
if sign_iter==1
    sign_dummy = -1;
    sign_string='cut';
elseif sign_iter==2
    sign_dummy = 0;
    sign_string='hike';
else
    error('Case not implemented')
end

%the naming of the following needs to be consistent with the field names in the pos structure
if shock_iter==1
    impulse_name = 'PF_shock_G';
    shock_string='g';
elseif shock_iter==2
    impulse_name = 'PF_shock_T';
    shock_string='t';
else
    error('Case not implemented')
end

save_string = strcat(shock_string,sign_string);

lag_number=4;
max_irf_horizon = 8;
time_fixed_effects_dummy=1;
country_fixed_effects_dummy=1;

add_residual_dummy=1; %adds residuals from previous step to regression to increase efficiency;


%% Construct sample

% Load data arrays for regression
load('../Figure 3+6 + Appendix C Descriptives/dataset_BDMP.mat');
temp=load('../Sign_restriction_first_stage_shocks_euro_area/results/structural_shocks_point.mat');

data_array_for_regression_stacked_by_variable = cat(3,data_array_for_regression_stacked_by_variable,temp.structural_shocks.BP_G,temp.structural_shocks.BP_T,temp.structural_shocks.PF_G,temp.structural_shocks.PF_T);
pos.BP_shock_G_CK=length(fieldnames(pos))+1;
Header{1,pos.BP_shock_G_CK}='BP_shock G based on Caldara/Kamps';
pos.BP_shock_T_CK=length(fieldnames(pos))+1;
Header{1,pos.BP_shock_T_CK}='BP_shock T based on Caldara/Kamps';
pos.PF_shock_G=length(fieldnames(pos))+1;
Header{1,pos.PF_shock_G}='Sign restriction shock G based on Caldara/Kamps';
pos.PF_shock_T=length(fieldnames(pos))+1;
Header{1,pos.PF_shock_T}='Sign restriction shock T based on Caldara/Kamps';

if length(Header)~=length(fieldnames(pos)) ||  length(Header)~=size(data_array_for_regression_stacked_by_variable,3)
    error('Header is not correctly defined')
end

% check whether positions are unique
pos_numbers=cell2mat(struct2cell(pos));
unique_pos_numbers=unique(pos_numbers);
if ~isequal(pos_numbers,unique_pos_numbers)
    pos_numbers(~ismember(pos_numbers,unique_pos_numbers))
    error('The position numbers are wrong')
end
% Set dependent variables and regressors
regressor_var_names={'g_real_demeaned_linearly_detrended', 'y_real_demeaned_linearly_detrended', 'Effective_FX_Real_Intra_Euro_CPI_log', 'tax_revenue_real_demeaned_detrended'};
dependent_var_names={'g_real_demeaned_linearly_detrended','y_real_demeaned_linearly_detrended','Effective_FX_Real_Intra_Euro_CPI_log', 'tax_revenue_real_demeaned_detrended'};

if lag_number<1
    error('Lag number must be strictly positive')
end


%euro countries only
[row,col] = find(data_array_for_regression_stacked_by_variable(:,:,pos.euro_country)==0);

for ii=1:length(row)
    data_array_for_regression_stacked_by_variable(row(ii),col(ii),3:end)=NaN;
end

fe_shocks_temp = data_array_for_regression_stacked_by_variable(:,:,pos.(impulse_name));

fe_shocks_negative = zeros(size(fe_shocks_temp));
fe_shocks_negative(fe_shocks_temp<0 | isnan(fe_shocks_temp)) = fe_shocks_temp(fe_shocks_temp<0 | isnan(fe_shocks_temp));
fe_shocks_positive = zeros(size(fe_shocks_temp));
fe_shocks_positive(fe_shocks_temp>0 | isnan(fe_shocks_temp)) = fe_shocks_temp(fe_shocks_temp>0 | isnan(fe_shocks_temp));
if any(any(fe_shocks_negative>0)) || any(any(fe_shocks_positive<0 ))
    error('Sign is wrong')
end

if sign_dummy==-1
    data_array_for_regression_impulse_only=cat(3,fe_shocks_negative,fe_shocks_positive);
elseif sign_dummy==1
    data_array_for_regression_impulse_only=cat(3,fe_shocks_positive,fe_shocks_negative);
elseif sign_dummy==0
    data_array_for_regression_impulse_only=cat(3,fe_shocks_temp);
else
    error('undefined case for sign_dummy')
end

data_array_for_regression=data_array_for_regression_impulse_only;

%% Lagged regressors
for var_iter=1:length(regressor_var_names)
    data_array_control=data_array_for_regression_stacked_by_variable(:,:,pos.([regressor_var_names{var_iter},'_lag_1']):pos.([regressor_var_names{var_iter},'_lag_',num2str(lag_number)]));
    data_array_for_regression=cat(3,data_array_for_regression,data_array_control);
end

%% Run regression

theta_mat=NaN(1+max_irf_horizon,length(dependent_var_names));
se_mat=NaN(1+max_irf_horizon,length(dependent_var_names));
theta_table = NaN(8, 10);

for var_iter=1:length(dependent_var_names)
    for horizon_iter = 0:max_irf_horizon
        %construct matrices without NaN
        if horizon_iter==0
            dependent_variable=squeeze(data_array_for_regression_stacked_by_variable(:,:,pos.(dependent_var_names{var_iter})));
            yhat_full=NaN(size(dependent_variable));
            [dependent_variable_for_run,data_array_for_regression_for_run,time_indices_non_NaN,country_indices_non_NaN]=create_regression_matrices_no_NaN(dependent_variable,data_array_for_regression,data_array_for_regression_stacked_by_variable,pos,country_indicator_names_mapping,time_fixed_effects_dummy,country_fixed_effects_dummy);
            %run regression
            [theta,stdDK,~,CovDK,yhat] = HszDk5cPs(dependent_variable_for_run,ones(size(dependent_variable_for_run,1),1),data_array_for_regression_for_run,1,7,1);

            if add_residual_dummy && ~strcmp(impulse_name,dependent_var_names(var_iter)) %when regression G on itself, residuals are 0
                yhat_full(time_indices_non_NaN,country_indices_non_NaN)=yhat;
                resids=dependent_variable-yhat_full;
            else
                resids=[];
            end
        else
            dependent_variable=squeeze(data_array_for_regression_stacked_by_variable(:,:,pos.([dependent_var_names{var_iter},'_lead_',num2str(horizon_iter)])));
            yhat_full=NaN(size(dependent_variable));

            [dependent_variable_for_run,data_array_for_regression_for_run,time_indices_non_NaN,country_indices_non_NaN]=create_regression_matrices_no_NaN(dependent_variable,cat(3,data_array_for_regression,resids),data_array_for_regression_stacked_by_variable,pos,country_indicator_names_mapping,time_fixed_effects_dummy,country_fixed_effects_dummy);
            %run regression
            [theta,stdDK,~,CovDK,yhat] = HszDk5cPs(dependent_variable_for_run,ones(size(dependent_variable_for_run,1),1),data_array_for_regression_for_run,1,7,1);
            if add_residual_dummy
                yhat_full(time_indices_non_NaN,country_indices_non_NaN)=yhat;
                resids=dependent_variable-yhat_full;
            else
                resids=[];
            end
        end

        %save coefficients
        theta_mat(1+horizon_iter,var_iter) = theta(1,1);
        se_mat(1+horizon_iter,var_iter)  = stdDK(1,1)';
    end
end

save(['LP_coefficients/' save_string],'theta_mat','se_mat')